import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/pages/login/lisence_widget.dart';
import 'package:yysk_app/pages/main/main_controller.dart';
import 'package:yysk_app/pages/my_webview/my_webview_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/collection_detail/collection_detail_controller.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/count_down_timer.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/text_linear_gradient_widget.dart';

/// 首发支付
class FirstPayFooter extends StatelessWidget {
  final CollectionDetailController controller;

  // final isRead = false.obs;
  GlobalController globaController = Get.find();
  // final String price;
  // final int id;
  final String type;
  FirstPayFooter({
    super.key,
    required this.controller,
    // required this.price,
    // required this.id,
    required this.type,
  });

  // final MainController mainController = Get.find();

  @override
  Widget build(BuildContext context) {
    return _setUpTime();
  }

  void _handlePay(BuildContext context) {
    if (controller.isRead.value) {
      if (globaController.hasAuth.value == true) {
        controller.createFirstOrder();
      } else {
        controller.toSm(context: context);
      }
    } else {
      showToast('请阅读理解并同意协议');
    }
  }

  _buy({
    String txt = '立即购买',
    required int userCanBuyCount,
    required CollectionDetailController controller,
    required int firstPublishGroupCount,
  }) {
    var list = [];
    final type = controller.showType.value; ////显示优先购为 1 优先抢 为 2 ，公售为3
    if (type == '1') {
      list = controller.firstDetail.value!.priorityBuyConditionList ?? [];
    } else if (type == "2") {
      list = controller.firstDetail.value!.priorityRobConditionList ?? [];
    } else {
      list = controller.firstDetail.value!.publicConditionList ?? [];
    }
    return Obx(
      () => Center(
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(color: Color.fromRGBO(12, 14, 18, 1)),
              padding: EdgeInsets.only(
                left: 14.px,
                right: 14.px,
                bottom: 20.px,
                top: controller.showRule.value ? 10.px : 0,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 2.px,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          width: 1.px,
                          color: AppColors.backgroundColorGreyF8,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 6.px),
                  Row(
                    children: [
                      CheckboxWidget(
                        onChanged: (val) {
                          controller.isRead.value = val;
                        },
                        checked: controller.isRead.value,
                      ),
                      SizedBox(width: 6.px),
                      Text(
                        '我已阅读并同意',
                        style: TextStyle(
                          fontSize: 12.px,
                          color: AppColors.backgroundColorGrey,
                        ),
                      ),
                      InkWell(
                        onTap: () async {
                          Get.toNamed(
                            '${MyWebViewPage.path}?url=${Uri.encodeComponent(globaController.staticInfo.value?.disclaimer ?? '')}',
                            arguments: {
                              'url': Uri.encodeComponent(
                                globaController.staticInfo.value?.disclaimer ??
                                    '',
                              ),
                            },
                          );
                        },
                        child: Text(
                          '《平台首发数字藏品免责声明》',
                          style: TextStyle(
                            color: AppColors.backgroundColorGreenLight,
                            fontSize: 12.px,
                          ),
                        ),
                      ),
                    ],
                  ),

                  hiSpace(height: 10.px),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      RichText(
                        text: TextSpan(
                          children: [
                            TextSpan(
                              text: '￥',
                              style: TextStyle(
                                fontSize: 14.px,
                                color: AppColors.startColor,
                              ),
                            ),
                            TextSpan(
                              text: controller.amount.value,
                              style: TextStyle(
                                color: AppColors.startColor,
                                fontSize: 20.px,
                                fontWeight: FontWeight.w500,
                              ),
                            ),

                            TextSpan(
                              text:
                                  '  已售 ${controller.firstDetail.value?.showSoldCount ?? '暂无数据'}',
                              style: TextStyle(
                                color: AppColors.backgroundColorGrey,
                                fontSize: 15.px,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Row(
                        children: [
                          Container(
                            clipBehavior: Clip.antiAlias,
                            decoration: BoxDecoration(
                              color: AppColors.backgroundColorGrey2,
                              borderRadius: BorderRadius.circular(8.px),
                            ),
                            child: Row(
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    controller.subtract();
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(),
                                    width: 40.px,
                                    height: 30.px,
                                    child: Center(
                                      child: Stack(
                                        children: [
                                          Center(
                                            child: Container(
                                              width: 11.px,
                                              height: 2.px,
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(100),
                                                color: AppColors.fontColor,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),

                                Container(
                                  constraints: BoxConstraints(minWidth: 20.px),
                                  // width: 50.px,
                                  child: Center(
                                    child: Text(
                                      '${controller.buyNum.value}',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        color: AppColors.startColor,
                                        fontSize: 20.px,
                                        fontWeight: FontWeight.w500,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    // consoleLog('add');
                                    controller.add();
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(),
                                    // color: AppColors.fontColorRed,
                                    width: 40.px,
                                    height: 30.px,
                                    child: Center(
                                      child: Stack(
                                        children: [
                                          Center(
                                            child: Container(
                                              width: 2.px,
                                              height: 11.px,
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(100),
                                                color: AppColors.fontColor,
                                              ),
                                            ),
                                          ),
                                          Center(
                                            child: Container(
                                              width: 11.px,
                                              height: 2.px,
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(100),
                                                color: AppColors.fontColor,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(width: 8.px),
                          GestureDetector(
                            onTap: () {
                              controller.max();
                            },
                            child: Container(
                              height: 30.px,
                              padding: EdgeInsets.fromLTRB(10.px, 0, 10.px, 0),
                              decoration: BoxDecoration(
                                color: AppColors.backgroundColorGrey2,
                                borderRadius: BorderRadius.circular(8.px),
                              ),
                              child: Center(
                                child: Text(
                                  '最大',
                                  style: TextStyle(
                                    fontSize: 12.px,
                                    color: AppColors.fontColor,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: 13.px),

                  ButtonWidget(
                    label: txt,
                    width: 347.px,
                    height: 40.px,
                    fontSize: 16.px,
                    fontWeight: FontWeight.bold,
                    onPressed: () {
                      _handlePay(Get.context!);
                    },
                    // ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _otherType({
    required String txt,
    bool showCount = false,
    double timer = (60 * 30 * 1000),
  }) {
    return Padding(
      padding: EdgeInsets.only(top: 10.px, bottom: 20.px),
      child: Center(
        child: Stack(
          children: [
            Center(
              child: Container(
                width: 322.px,
                height: 40.px,
                decoration: BoxDecoration(
                  color: Color.fromRGBO(57, 231, 255, 0.2),
                  borderRadius: BorderRadius.circular(100),
                ),
              ),
            ),
            SizedBox(
              height: 40.px,
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    if (showCount)
                      CountdownTimer(
                        showHours: true,
                        fontSize: 18.px,
                        expireTime:
                            (DateTime.now().millisecondsSinceEpoch +
                                timer), // 替换为实际的过期时间戳
                        fontColor: AppColors.startColor,
                        onPressed: () {
                          controller.showBuyButton.value = true; //直接显示购买按钮
                          // controller.getProductDetail();
                        },
                      ),
                    SizedBox(width: 5.px),
                    Text(
                      txt,
                      style: TextStyle(
                        fontSize: 18.px,
                        color: AppColors.startColor,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _setUpTime() {
    final detail = controller.firstDetail.value; //详情数据/第一次拿拿就好
    final nowTime = DateTime.now().microsecondsSinceEpoch / 1000; //目前时间
    final publishTime = controller.firstPublishTime.value; //这个是定时器获取时间用的
    final twelveHours = 60 * 12 * 60 * 1000; //十二小时
    //优先购开始时间戳
    final priorityBuyStartTimeMilli =
        DateTime.parse(
          publishTime!.priorityBuyStartTime ?? '2099-07-08 17:10:00',
        ).millisecondsSinceEpoch;
    //优先购结束时间戳
    final priorityBuyEndTimeMilli =
        DateTime.parse(
          publishTime.priorityBuyEndTime ?? '2099-07-08 17:10:00',
        ).millisecondsSinceEpoch;
    //优先抢开始时间戳
    final priorityRobStartTimeMilli =
        DateTime.parse(
          publishTime.priorityRobStartTime ?? '2099-07-08 17:10:00',
        ).millisecondsSinceEpoch;
    //	优先抢结束时间戳
    final priorityRobEndTimeMilli =
        DateTime.parse(
          publishTime.priorityRobEndTime ?? '2099-07-08 17:10:00',
        ).millisecondsSinceEpoch;
    //	公售开始时间戳
    final publicSaleStartTimeMilli =
        DateTime.parse(publishTime.publicSaleStartTime!).millisecondsSinceEpoch;
    //	公售结束时间戳
    final publicSaleEndTimeMilli =
        DateTime.parse(publishTime.publicSaleEndTime!).millisecondsSinceEpoch;
    consoleLog('${nowTime}======目前时间');
    consoleLog('${twelveHours}======12小时时间');
    consoleLog('${priorityBuyStartTimeMilli}======优先购开始时间戳');
    consoleLog('${priorityBuyEndTimeMilli}======优先购结束时间戳');
    consoleLog('${priorityRobStartTimeMilli}======优先抢开始时间戳');
    consoleLog('${priorityRobEndTimeMilli}======优先抢结束时间戳');
    consoleLog('${publicSaleStartTimeMilli}======公售开始时间戳');
    consoleLog('${publicSaleEndTimeMilli}======公售结束时间戳');
    if (controller.showBuyButton.value == true) {
      return _buy(
        userCanBuyCount: detail!.userCanBuyCount ?? 0,
        controller: controller,
        firstPublishGroupCount: detail.firstPublishGroupCount ?? 0,
      );
    }
    //  return _buy(
    //   userCanBuyCount: detail?.userCanBuyCount ?? 0,
    //   controller: controller,
    // ); //购买
    // return _otherType(txt: '公售', timer: 3000, showCount: true);
    // detail.saleStatus这个状态暂时先拿住先用mock数据的
    if (detail!.saleStatus == 'COMPLETED') {
      return _otherType(txt: '已结束');
    }
    if (detail.saleStatus == 'SOLD_OUT') {
      return _otherType(txt: '已售罄');
    }
    if (!detail.isCanPriorityBuy! && !detail.isCanPriorityRob!) {
      controller.showType.value = '3';
      //不满足优先购和优先抢  直接显示公售时间或者倒计时
      if (nowTime < publicSaleStartTimeMilli) {
        //当前时间在公售开始之前
        if (nowTime > (publicSaleStartTimeMilli - twelveHours)) {
          //判断是否是12小时之内

          final countDown = publicSaleStartTimeMilli - nowTime; //开始前倒计时时间
          return _otherType(txt: '公售', timer: countDown, showCount: true);
        } else {
          //不在3分钟之内
          return _otherType(txt: '${detail.publicSaleStartTime}公售');
        }
      } else if (nowTime < publicSaleEndTimeMilli) {
        //公售结束之前
        // 设置上限
        // controller.maxNum.value = detail.personalPublicCap!;
        // return _otherType(txt: '已结束');
        return _buy(
          userCanBuyCount: detail.userCanBuyCount ?? 0,
          controller: controller,
          firstPublishGroupCount: detail.firstPublishGroupCount ?? 0,
        ); //购买
      }
    }

    //下一步 优先购逻辑
    if (detail.isCanPriorityBuy! &&
        priorityBuyStartTimeMilli > nowTime &&
        nowTime < priorityBuyEndTimeMilli) {
      controller.showType.value = '1';
      //首先有优先购资格且 优先购开始时间 当时的时间
      if (nowTime > priorityBuyStartTimeMilli - twelveHours) {
        //判断是否是12小时之内
        final countDown = priorityBuyStartTimeMilli - nowTime; //开始前倒计时时间
        return _otherType(txt: '优先购', timer: countDown, showCount: true);
      } else {
        //不在12小时之内
        return _otherType(txt: '${detail.priorityBuyStartTime}优先购');
      }
    } else if (detail.isCanPriorityBuy! && nowTime < priorityBuyEndTimeMilli) {
      //首先有优先购资格且 在优先购的时间内  //可以购买
      // 设置上限
      // controller.maxNum = detail.personalPriorityBuyCap!;
      controller.showType.value = '1';

      return _buy(
        userCanBuyCount: detail.userCanBuyCount ?? 0,
        controller: controller,
        firstPublishGroupCount: detail.firstPublishGroupCount ?? 0,
      ); //购买
    }
    //上述可能是有优先购资格，但是已经过了优先购时间

    //下一步 优先抢逻辑
    if (detail.isCanPriorityRob! &&
        priorityRobStartTimeMilli > nowTime &&
        nowTime < priorityRobEndTimeMilli) {
      controller.showType.value = '2';
      //首先有优先抢资格且 优先抢开始时间 当时的时间
      if (nowTime > priorityRobStartTimeMilli - twelveHours) {
        //判断是否是12小时之内
        final countDown = priorityRobStartTimeMilli - nowTime; //开始前倒计时时间
        return _otherType(txt: '优先抢', timer: countDown, showCount: true);
      } else {
        //不在12小时之内
        return _otherType(txt: '${detail.priorityRobStartTime}优先抢');
      }
    } else if (detail.isCanPriorityRob! && nowTime < priorityRobEndTimeMilli) {
      // 设置上限
      // controller.maxNum = detail.personalPriorityRobCap!;
      controller.showType.value = '2';

      return _buy(
        userCanBuyCount: detail.userCanBuyCount ?? 0,
        controller: controller,
        firstPublishGroupCount: detail.firstPublishGroupCount ?? 0,
      ); //购买
    }
    //上述可能是有优先购,优先抢资格，但是已经过了优先购,优先抢时间
    //下面逻辑可能是 我有优先购,优先抢资格，但是时间否过了，我要显示 普通购买逻辑
    //最后的逻辑需要把 分支走死。必须抛出
    if (nowTime < publicSaleStartTimeMilli) {
      controller.showType.value = '3';
      //当前时间在公售开始之前
      if (nowTime > publicSaleStartTimeMilli - twelveHours) {
        //判断是否是3分钟之内
        final countDown = publicSaleStartTimeMilli - nowTime; //开始前倒计时时间
        return _otherType(txt: '公售', timer: countDown, showCount: true);
      } else {
        //不在3分钟之内
        return _otherType(txt: '${detail.publicSaleStartTime}公售');
      }
    } else if (nowTime < publicSaleEndTimeMilli) {
      controller.showType.value = '3';
      //公售结束之前
      // 设置上限
      // controller.maxNum = detail.personalPublicCap!;

      return _buy(
        userCanBuyCount: detail.userCanBuyCount ?? 0,
        controller: controller,
        firstPublishGroupCount: detail.firstPublishGroupCount ?? 0,
      ); //购买
    } else {
      return _otherType(txt: '已结束');
    }
  }
}
